/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：登录通-测试工程
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taiping.dlt.webapi.test.app.authorize;

import com.taipingframework.boot.cache.constant.DurationConstant;
import com.taipingframework.boot.cache.redis.StandardCacheKeyBuilder;
import com.taipingframework.boot.dlt.AuthorizeActionCallback;
import com.taipingframework.boot.web.client.BrowserCookie;
import com.taipingframework.boot.web.client.ReactiveCookieScene;
import com.taipingframework.utility.extend.ReactorHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.time.Duration;

@Slf4j
@Component
public class SessionActionCallback implements AuthorizeActionCallback {

    /**
     * 登录回调
     */
    @Override
    public Mono<Void> loginCallback() {
        String cookieName = StandardCacheKeyBuilder.getAuthTokenKey();
        return ReactorHelper.getExchange()
                .subscribeOn(Schedulers.boundedElastic())
                .map(exchange -> exchange.getAttribute(cookieName))
                .map(cookieValue -> new BrowserCookie(cookieName, String.valueOf(cookieValue), DurationConstant.HOUR_12.instance()))
                .flatMap(ReactiveCookieScene::writeWebCookie)
                .doOnSuccess(aVoid -> log.info("登录回调 - 将会话标识写入浏览器Cookie"));
    }

    /**
     * 退出登录回调
     */
    @Override
    public Mono<Void> logoutCallback() {
        String cookieName = StandardCacheKeyBuilder.getAuthTokenKey();
        return Mono.fromSupplier(() -> new BrowserCookie(cookieName, StringUtils.EMPTY, Duration.ZERO))
                .subscribeOn(Schedulers.boundedElastic())
                .flatMap(ReactiveCookieScene::writeWebCookie)
                .doOnSuccess(aVoid -> log.info("退出回调 - 删除浏览器Cookie的会话标识"));
    }

}
